# -*- coding: utf-8 -*-
# time: 2025/5/20 13:47
# file: mdns.py
# author: hanson


from zeroconf import ServiceInfo, Zeroconf
import socket


def publish_service():
    service_type = "_http._tcp.local."
    service_name = "a_hanson._http._tcp.local."
    port = 8087
    desc = {'path': '/', 'version': '1.0'}

    # 获取本机IP
    hostname = socket.gethostname()

    local_ip = socket.gethostbyname(hostname)

    service_info = ServiceInfo(
        service_type,
        service_name,
        addresses=[socket.inet_aton(local_ip)],
        port=port,
        properties=desc,
        server=hostname + ".local.",
    )

    zeroconf = Zeroconf()
    zeroconf.register_service(service_info)
    print(f"Published service: {service_name}")

    try:
        input("Press enter to exit...\n\n")
    finally:
        zeroconf.unregister_service(service_info)
        zeroconf.close()


if __name__ == "__main__":
    publish_service()